package jsr292.java.lang.invoke;

import java.lang.reflect.Array;

import jsr292.weaver.Debug;
import jsr292.weaver.opt.OptimizerContext;
import jsr292.weaver.opt.OptimizerSnippets;
import jsr292.weaver.opt.OptimizerVarAllocator;

public class MHArrayElementGetter extends MethodHandle {
    private final Class<?> arrayClass;
    
    public MHArrayElementGetter(Class<?> arrayClass) {
        super(MethodType.methodType(arrayClass.getComponentType(), arrayClass, int.class));
        this.arrayClass = arrayClass;
    }
  
    @Override
    public Object $invoke$(Object o1, Object o2) throws Throwable {
        return Array.get(o1, (Integer)o2);
    }
    
    @Override
    public boolean isWeavable(Class<?> classBeingRedefined) {
        return true;
    }
    
    @Override
    public void weave(OptimizerContext context, OptimizerVarAllocator allocator) {
        if (Debug.DEBUG) {
            Debug.checkAllocator(allocator, this);
        }
        
        OptimizerSnippets.arrayGetter(context, allocator, arrayClass);
    }
}
